package com.kitty.game.activity.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

import org.nutz.lang.util.NutMap;
import org.springframework.stereotype.Service;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.ActivityDataPool;
import com.kitty.game.activity.model.product.ActivityLivenessRewardSet;
import com.kitty.game.activity.model.product.ActivityLivenessSet;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.seal.SealBossHandler;
import com.kitty.game.activity.service.task.ShuaDaoTaskHandler;
import com.kitty.game.activity.service.task.TaskActivityHandler;
import com.kitty.game.config.OnlineMall;
import com.kitty.game.config.TaskSet;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.role.ActivityData;
import com.kitty.game.role.ActivityRewardStatus;
import com.kitty.game.role.message.RespLivenessInfo;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.model.Member;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.common.model.Reason;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;

/**活动业务类*/
@Service
public class ActivityService {

    /**获得活动完成次数*/
    public int getFinishCount(Role role, ActivityType activityType) {
        return role.getActivity().getFinishCounts().getInt(activityType.getActivityId(), 0);
    }

    /**增加活动完成次数*/
    public void addFinishCount(Role role, ActivityType activityType, int addCount) {
        int activityCount = role.getActivity().getFinishCounts().getInt(activityType.getActivityId(), 0);
        int count = activityCount + addCount;
        role.getActivity().getFinishCounts().put(activityType.getActivityId(), count);
        /**增加活跃度*/
        ActivityLivenessSet activityLivenessSet = ActivityDataPool.activityLivenessSetMapByType.get(activityType);
        if (activityLivenessSet != null) {
            int livenessCount = (int)(activityLivenessSet.getMaxLiveness()/activityLivenessSet.getPerLiveness());
            if (count <= livenessCount) {
                float addLiveness = activityLivenessSet.getPerLiveness() * addCount;
                role.getActivity().setLiveness(role.getActivity().getLiveness() + addLiveness);
            }
        }

        role.save();
    }
    /**减少活动完成次数*/
    public void reduceFinishCount(Role role, ActivityType activityType, int reduceCount) {
        int activityCount = role.getActivity().getFinishCounts().getInt(activityType.getActivityId(), 0);
        int count = activityCount - reduceCount;
        role.getActivity().getFinishCounts().put(activityType.getActivityId(), count);
        role.save();
    }
/*应该是充值获得上古次数*/
    public int getRemainCount(Role role, ActivityType activityType) {
        int finishCount = getFinishCount(role, activityType);
        int totalCount = activityType.getTotalCount();
        if (finishCount > totalCount) {
            return 0;
        }
        return totalCount - finishCount;
    }

    /**活动是否还有剩余次数*/
    public boolean isHaveRemainCount(Role role, ActivityType activityType) {
        int count = getRemainCount(role,activityType);
        if (count <= 0){
            return false;
        }
        return true;
    }

    /**重置每日活动*/
    public void dailyResetActivity(Role role) {
        role.getActivity().dailyReset();
        role.setGold2money(NutMap.NEW());

        resetActivityTask(role);
        SpringUtils.getBean(ShuaDaoTaskHandler.class).resetScoreAndSendReward(role);
    }

    /**重置任务*/
    private void resetActivityTask(Role role) {
        ActivityDataPool.activityHandlers.stream().forEach((ActivityHandler activityHandler)-> {
            if (activityHandler instanceof TaskActivityHandler) {
                if (activityHandler instanceof ShuaDaoTaskHandler){
                    return;
                }
                TaskSet taskSet = ((TaskActivityHandler)activityHandler).getTaskSetByType(role);
                if (taskSet == null) {return ;}

                role.getTask().resetTask(taskSet.getId());
                role.save();
            }
        });
    }



    public void handleFightEnd(FightEndEvent fightEndEvent) {
        ActivityDataPool.activityHandlers.stream().forEach((ActivityHandler activityHandler)-> {activityHandler.handleFightEnd(fightEndEvent);});
    }

    public void handleLeaveTeam(Role role, boolean leader, List<Member> memberList) {
        ActivityDataPool.activityHandlers.stream().forEach((ActivityHandler activityHandler)-> {activityHandler.handleTeamLeave(role, leader, memberList);});
    }

    public void handleTeamLeaveMonment(Role role) {
        ActivityDataPool.activityHandlers.stream().forEach((ActivityHandler activityHandler)-> {activityHandler.handleTeamLeaveMonment(role);});
    }

    public void handleTeamChangeLeader(Role role, List<Member> memberList) {
        ActivityDataPool.activityHandlers.stream().forEach((ActivityHandler activityHandler)-> {activityHandler.handleTeamChangeLeader(role, memberList);});
    }

    public void handleLogout(Role role) {
        ActivityDataPool.activityHandlers.stream().forEach((ActivityHandler activityHandler)-> {activityHandler.handleLogout(role);});
    }

    public void handleLogin(Role role) {
        ActivityDataPool.activityHandlers.stream().forEach((ActivityHandler activityHandler)-> {activityHandler.handleLogin(role);});
    }

    public void handleHeartBeat(Role role, long prevHeartTime) {
        ActivityDataPool.activityHandlers.stream().forEach((ActivityHandler activityHandler)-> {activityHandler.handleHeartBeat(role, prevHeartTime);});
    }

    public void handleTalkEnd(Role role) {
        Object popChooseParam = role.popTempCache("fight_seal_boss_map");
        if (popChooseParam != null) {
            Object handler = role.popTempCache("fight_seal_boss_handler");
            ((SealBossHandler)SpringUtils.getBean((Class)handler)).fightConfirm(role, (Integer)popChooseParam);
        }
    }

    public void handleRoleExpire(Role role) {
        ActivityDataPool.activityHandlers.stream().forEach((ActivityHandler activityHandler)-> {activityHandler.handleRoleExpire(role);});
    }

    /**获得活跃度信息返回包*/
    public RespLivenessInfo getRespLivenessInfo(Role role) {
        /** 获取活跃度信息*/
        RespLivenessInfo respLivenessInfo = new RespLivenessInfo();
        respLivenessInfo.setActivityData(getActivityData(role));
        respLivenessInfo.setRewardStatus(getActivityRewardStatus(role));
        return respLivenessInfo;
    }

    /**获得活动完成次数数据*/
    private List<ActivityData> getActivityData(Role role) {
        List<ActivityData> activityDataList = new ArrayList<>(ActivityDataPool.activityLivenessSetMapByName.size());
        for (Map.Entry<String, ActivityLivenessSet> entry : ActivityDataPool.activityLivenessSetMapByName.entrySet()) {
            String name = entry.getKey();
            ActivityLivenessSet activityLivenessSet = entry.getValue();
            ActivityData activityData = new ActivityData();
            activityData.setName(name);
            int finishCount = activityLivenessSet.getActivityTypeList().stream().mapToInt((ActivityType activityType) -> SpringUtils.getActivityService().getFinishCount(role, activityType)).sum();
            activityData.setCount((short) finishCount);
            int liveness = (int)(finishCount * activityLivenessSet.getPerLiveness());
            activityData.setActiveValue((short) ((liveness > activityLivenessSet.getMaxLiveness() ? activityLivenessSet.getMaxLiveness() : liveness) * ActivityDataPool.LIVENESS_RATIO));
            activityDataList.add(activityData);
        }

        return activityDataList;
    }

    /**获得活动活跃度奖励状态*/
    private List<ActivityRewardStatus> getActivityRewardStatus(Role role) {
        List<ActivityRewardStatus> rewardStatusList = new ArrayList<>();
        for (ActivityLivenessRewardSet activityLivenessRewardSet : ActivityDataPool.activityLivenessRewardSets) {
            ActivityRewardStatus activityRewardStatus = new ActivityRewardStatus();
            activityRewardStatus.setActivity((short)activityLivenessRewardSet.getLivenessCount());
            activityRewardStatus.setStatus(getActivityRewardStatus(role, activityLivenessRewardSet));
            rewardStatusList.add(activityRewardStatus);
        }
        return rewardStatusList;
    }

    private byte getActivityRewardStatus(Role role, ActivityLivenessRewardSet activityLivenessRewardSet) {
        if (isFetchLivenessReward(role, activityLivenessRewardSet)) {return ActivityLivenessRewardSet.FETCHED;}
        if (role.getActivity().getLiveness() >= activityLivenessRewardSet.getLivenessCount()) {return ActivityLivenessRewardSet.CAN_FETCH;}

        return 0;
    }

    /**是否已经领取对应活跃度的奖励*/
    private boolean isFetchLivenessReward(Role role, ActivityLivenessRewardSet activityLivenessRewardSet) {
        Boolean isFetched = role.getActivity().getLivenessRewardFetchStatus().get(activityLivenessRewardSet.getLivenessCount());
        if (isFetched == null) {
            return false;
        }
        return isFetched;
    }

    /**领取活跃度奖励*/
    public void fetchLivenessReward(Role role, int livenessCount) {
        ActivityLivenessRewardSet activityLivenessRewardSet = getActivityLivenessRewardSet(livenessCount);
        if (activityLivenessRewardSet == null) {return ;}

        /**判断是否已经领取*/
        if (isFetchLivenessReward(role, activityLivenessRewardSet)) {
            return ;
        }
        /**判断是否有对应的活跃度值*/
        if (role.getActivity().getLiveness() < activityLivenessRewardSet.getLivenessCount()) {
            return ;
        }


        /**设置为已经领取*/
        role.getActivity().getLivenessRewardFetchStatus().put(activityLivenessRewardSet.getLivenessCount(), true);


        /**给奖励*/
        if (activityLivenessRewardSet.getRewardName().equals("银元宝")) {
            SpringUtils.getRoleService().addSiver(role, activityLivenessRewardSet.getRewardCount(), Reason.FETCH_LIVENESS_REWARD);
        } else if (activityLivenessRewardSet.getRewardName().equals("活跃度宝箱")){
            List<OnlineMall> list = DataCache.NAME_MALL.values().stream().filter(onlineMail -> onlineMail.getPrice()<=1000).collect(Collectors.toList());
            int index = ThreadLocalRandom.current().nextInt(list.size());
            OnlineMall onlineMall = list.get(index);
            SpringUtils.getEquipService().addMall(onlineMall.getName(), true, role, activityLivenessRewardSet.getRewardCount());
        } else if(activityLivenessRewardSet.getRewardName().equals("积分")){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("领取"+activityLivenessRewardSet.getRewardCount()+"积分"));
            SpringUtils.getRoleService().addRechargeScore(role, activityLivenessRewardSet.getRewardCount());
        }else {
            SpringUtils.getEquipService().addMall(activityLivenessRewardSet.getRewardName(), true, role, activityLivenessRewardSet.getRewardCount());
        }
        role.save();
    }

    private ActivityLivenessRewardSet getActivityLivenessRewardSet(int livenessCount) {
        return ActivityDataPool.activityLivenessRewardSetMap.get(livenessCount);
    }

    /**是否开启急急如律令*/
    public boolean isOpenJJRLL(Role role) {
        int jijirulvling = role.getPropsStatus().getInt("manguaiStatus", 0);
        int kaiqi = role.getPropsStatus().getInt("manguai", 0);
        if (jijirulvling > 0 && kaiqi > 0) {
            return true;
        }

        return false;
    }


}
